import allure
import pytest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from autoTest_ecshop.utils.db_util import mydb

@pytest.fixture(scope='session')
def driver():
    # 定义全局变量
    global driver
    driver = webdriver.Edge()
    driver.maximize_window()
    # driver.implicitly_wait(10)
    url = 'http://localhost:8088/ecshop/'
    driver.get(url=url)
    # login_locator = (By.CSS_SELECTOR, 'font[id="ECS_MEMBERZONE"]>a:nth-of-type(1)>img')
    # login = WebDriverWait(driver, 5).until(EC.visibility_of_element_located(login_locator))
    # login.click()

    yield driver
    # driver.quit()
#     环境恢复
    sql_sel = 'select user_id from ecs_users where user_name="你是大傻逼";'
    res = mydb.query_one(sql_sel)
    print(res)
    user_id = res[0]
    print(user_id)

    sql = "select order_id from ecs_order_info where user_id=6;"
    res2 = mydb.query_one(sql)
    print(res2)
    order_id = res2[0]
    print(order_id)

    del1 = "delete from ecs_order_info where order_id= %s;" % user_id
    mydb.execteSQL(del1)
    del2 = "delete from ecs_order_info where user_id= %s;" % user_id
    mydb.execteSQL(del2)

## 钩子函数，获取结果
@pytest.hookimpl(hookwrapper=True,tryfirst=True)
def pytest_runtest_makereport(item,call):
    # 获取钩子函数的结果
    out = yield
    # 获取测试报告
    report = out.get_result()
    # 脚本执行失败，截图
    if report.when == 'call' and report.outcome == "failed":
        # 把脚本上传到allure报告
        allure.attach( driver.get_screenshot_as_png(),name="失败截图",\
                       attachment_type=allure.attachment_type.PNG)